<?php
/**
 * Created by PhpStorm.
 * User: qinpeizhou
 * Date: 2018年5月24日
 * Time: 20:40:43
 */
class HttpServer
{
    public static $instance;

    public $http = null;
    public static $get;
    public static $post;
    public static $header;
    public static $server;
    private $application;

    public function __construct() {
        $this->http = new swoole_http_server("0.0.0.0", 8811);

        $this->http->set(
            array(
                'enable_static_handler'=>true,
                'document_root'=> '/home/wwwroot/default/yafdemo/public/static',
                'worker_num' => 4,  // 开启的进程数
                'task_worker_num' => 4
//                'daemonize' => true,
//                'max_request' => 10000,
//                'dispatch_mode' => 1
            )
        );


        $this->http->on("workerstart", [$this, 'onWorkerStart']);
        $this->http->on("request", [$this, 'onRequest']);
        $this->http->on("task", [$this, 'onTask']);
        $this->http->on("finish", [$this, 'onFinish']);
        $this->http->on("close", [$this, 'onClose']);

        $this->http->start();
    }



    public function onWorkerStart($server,  $worker_id) {
        Yaf_Loader::import(dirname(__FILE__).'/../common/lib/Task.php');
        define('APPLICATION_PATH', dirname(__DIR__));
        $this->application = new Yaf_Application( APPLICATION_PATH .
            "/conf/application.ini");
        ob_start();
        $this->application->bootstrap()->run();
        ob_end_clean();
    }

    public function onRequest($request, $response) {
        // 转换成原生php
        $_SERVER  =  [];
        if(isset($request->server)) {
            HttpServer::$server =  $request->server;
            foreach($request->server as $k => $v) {
                HttpServer::$server[strtoupper($k)] = $v;
                $_SERVER[strtoupper($k)] = $v;
            }
        }
        if(isset($request->header)) {
            HttpServer::$header =  $request->header;
            foreach($request->header as $k => $v) {
                HttpServer::$server[strtoupper($k)] = $v;
                $_SERVER[strtoupper($k)] = $v;
            }
        }

        $_GET = [];
        if(isset($request->get)) {
            HttpServer::$get = $request->get;
            foreach($request->get as $k => $v) {
                HttpServer::$get[$k] = $v;
                $_GET[$k] = $v;
            }
        }
        $_POST = [];
        if(isset($request->post)) {
            HttpServer::$post = $request->post;
            foreach($request->post as $k => $v) {
                HttpServer::$post[$k] = $v;
                $_POST[$k] = $v;
            }
        }

        HttpServer::$post['http_server'] = $this->http;
        $_POST['http_server'] = $this->http;

       /* //转成HttpServer支持
        if( isset($request->server) ) {
            HttpServer::$server = $request->server;
        }else{
            HttpServer::$server = [];
        }
        if( isset($request->header) ) {
            HttpServer::$header = $request->header;
        }else{
            HttpServer::$header = [];
        }
        if( isset($request->get) ) {
            HttpServer::$get = $request->get;
        }else{
            HttpServer::$get = [];
        }
        if( isset($request->post) ) {
            HttpServer::$post = $request->post;
        }else{
            HttpServer::$post = [];
        }
        HttpServer::$post['http_server'] = $this->http;*/

        ob_start();
        try {
            $yaf_request = new Yaf_Request_Http(HttpServer::$server['request_uri']);
            $this->application->getDispatcher()->dispatch($yaf_request);

//             unset(Yaf_Application::app());
        } catch ( Yaf_Exception $e ) {
            var_dump( $e );
        }


        $result = ob_get_contents();

        ob_end_clean();

        // add Header

        // add cookies

        // set status
        $response->end($result);
    }

    /**
     * @param $serv
     * @param $taskId
     * @param $workerId
     * @param $data
     */
    public function onTask($serv, $taskId, $workerId, $data) {
        // 分发 task 任务机制，让不同的任务 走不同的逻辑
        $method = $data['method'];
        $flag = Task::getInstance()->$method($data['data']);
        /*$obj = new app\common\lib\ali\Sms();
        try {
            $response = $obj::sendSms($data['phone'], $data['code']);
        }catch (\Exception $e) {
            // todo
            echo $e->getMessage();
        }*/

        return $flag; // 告诉worker
    }

    /**
     * @param $serv
     * @param $taskId
     * @param $data
     */
    public function onFinish($serv, $taskId, $data) {
        echo "taskId:{$taskId}\n";
        echo "finish-data-sucess:{$data}\n";
    }

    /**
     * close
     * @param $ws
     * @param $fd
     */
    public function onClose($ws, $fd) {
        echo "clientid:{$fd}\n";
    }


    public static function getInstance() {
        if (!self::$instance) {
            self::$instance = new HttpServer;
        }
        return self::$instance;
    }

}

HttpServer::getInstance();
